package com.huixue.server.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.json.JSONException;
import org.json.JSONObject;

import com.huixue.server.basic.Common;
import com.huixue.server.basic.HttpUtil;
import com.huixue.server.interfaces.IRule;
import com.huixue.server.rule.VerifyToken;

public class Process extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Log logger = LogFactory.getLog(getClass()); // 日志对象
	private String className = getClass().getName();
	private static SqlSessionFactory factory = Common.getSqlSessionFactory();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String cmd = request.getHeader("cmd");
		String responseData = "{}"; // 等于null的空json对象
		SqlSession session = null;

		if (cmd != null) {
			String requestData = new HttpUtil()
					.ServletInputStreamToString(request.getInputStream());
			session = factory.openSession();
			// ***********************************************
			// 系统日志输出
			// ***********************************************
			logger
					.info(new StringBuffer(Common.getLogFlag(className))
							.append("\ncmd:").append(cmd).append("\n请求数据:")
							.append(requestData));
			VerifyToken verifyToken = new VerifyToken();
			if (verifyToken.verify(cmd, request.getCookies())) { // token有效
				// ***********************************************
				// 生成处理此请求的类的实例名称
				// ***********************************************
				String id = new StringBuffer("com.zpcx.aster.server.rule.Rule")
						.append(cmd).toString();
				try {
					IRule rule = (IRule) Class.forName(id).newInstance();
					responseData = rule.doIt(session, requestData);
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			} else {
				try {
					// ***********************************************
					// verify，0－验证成功；1－验证失败，如果客户端收到的应答没
					// 有这个参数就代表成功
					// ***********************************************
					responseData = (new JSONObject().put("verify", "1").put(
							"msg", "验证失败了吧，别在试了，在试你的电脑就爆炸了")).toString();
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}

		// ***********************************************
		// 应答给客户端
		// ***********************************************
		response.setHeader("cmd", cmd);
		response.setContentType("text/html;charset=UTF-8");
		response.getWriter().print(responseData);

		// ***********************************************
		// 系统日志输出
		// ***********************************************
		logger.info(new StringBuffer(Common.getLogFlag(className)).append(
				"\ncmd:").append(cmd).append("\n应答数据:").append(responseData));
	}

}
